const basePath = 'https://cnodejs.org';
const topicsUrl = '/api/v1/topics';
const detailUrl = '/api/v1/topic/';

// 获取首页主体
export async function getTopics({page = 1, limit = 10, tab = '', mdrender = 'false'}) {
    const response = await fetch(
        basePath + topicsUrl + `?page=${page}&limit=${limit}&tab=${tab}&mdrender=${mdrender}`
    );
    const data = await response.json();
    if (data && data.success) {
        return data.data;
    }
    throw new Error(data);
}

// 获取主题详情
export async function getTopDetail(id) {
    const response = await fetch(
        basePath + detailUrl + id
    );
    const data = await response.json();
    if (data && data.success) {
        return data.data;
    }
    throw new Error(data);
}

//获取最新回复
export async function getLastReply(id) {
    const response = await fetch(
        basePath + detailUrl + id
    );
    const data = await response.json();
    if (data && data.success) {
        const {replies} = data.data;
        return replies && replies[replies.length-1];
    }
    throw new Error(data);
}

/** 
 * 获取第一页文章列表中数据中,评论点赞数量最高十条评论
 * 1. 拉取第一页数据
 * 2. 循环每条数据，拉取详情数据
 * 3. 筛选详情数据中点赞最高的10条评论
 * **/
export async function fetchTop10() {
    const data = await getTopics({page:1});
    const promiseList = data.map((d) => 
        getTopDetail(d.id).then(detail => {
            const topReplies =  detail.replies.sort((a, b) => b.ups.length - a.ups.length).slice(0, 10);
            return {...d, replies: topReplies}
        })
    );
    const detailList = await Promise.all(promiseList);
    return detailList;
}